<template>
  <q-card style="min-width: 350px">
    <q-card-section>
      <div class="sub-header">Scan QR Code</div>
    </q-card-section>
    <div style="width: 300px; margin: auto">
      <qrcode-stream @init="onInit" @decode="onDecode"></qrcode-stream>
    </div>
    <q-card-section class="q-pt-none">
      <q-input
        dense
        v-model="decode"
        autofocus  
        @keydown.enter="submit"
        filled
      ></q-input>
    </q-card-section>

    <q-card-actions align="right" class="text-primary">
      <q-btn flat color="negative" label="Cancel" v-close-popup></q-btn>
      <q-btn flat label="Confirm" @click="submit"></q-btn>
    </q-card-actions>
  </q-card>
</template>

<script lang="ts">
import { QrcodeStream } from 'vue3-qrcode-reader';
import {ref} from 'vue'


export default {
  components: { QrcodeStream },
  emits:['submit'],
  setup(props,{emit}) {

    const onInit = async (promise:any) => {
      try {
        const { capabilities } = await promise;
        // successfully initialized
      } catch (error) {
        if (error.name === 'NotAllowedError') {
          this.error = 'user denied camera access permisson';
        } else if (error.name === 'NotFoundError') {
          this.error = 'no suitable camera device installed';
        } else if (error.name === 'NotSupportedError') {
          this.error = 'page is not served over HTTPS (or localhost)';
        } else if (error.name === 'NotReadableError') {
          this.error = 'maybe camera is already in use';
        } else if (error.name === 'OverconstrainedError') {
          this.error =
            'did you requested the front camera although there is none?';
        } else if (error.name === 'StreamApiNotSupportedError') {
          this.error = 'browser seems to be lacking features';
        }
      } finally {
        // hide loading indicator
      }
    };

    const decode = ref('')

    const onDecode = async (decodeString:string) => {
      console.log(decodeString)
      decode.value = decodeString
      submit()
    };

    
    function submit(){
      emit('submit', decode.value)
      decode.value = ''
    }

    return {
      onDecode,
      onInit,
      decode,
      submit
    };
  },
};
</script>
